import { defineConfig, type Plugin } from 'vite'
import react from '@vitejs/plugin-react'
import mockjs from 'mockjs'
import url from 'node:url'
const viteMockServer = (): Plugin => {
  return {
    name: 'vite-mock-server',
    //使用vite插件的钩子函数
    configureServer(server) {
      server.middlewares.use((req, res, next) => {
        if (req.originalUrl?.startsWith('/api')) {
          //url.parse 获取url参数 true表示返回对象 {keyWord: 'xx'}
          const query = url.parse(req.originalUrl, true).query;
          const data = mockjs.mock({
            'list|1000': [
              {
                'id|+1': 1,
                name: '@cword(3, 5)' + '_' + query.keyWord,
                'address': '@county(true)' // 随机生成县级地址
              },
            ],
          });
          res.setHeader('Content-Type', 'application/json');
          res.end(JSON.stringify(data));
        } else {
          next();
        }
      });
    }
  };
}
// https://vite.dev/config/
export default defineConfig({
  plugins: [react(), viteMockServer()],
  resolve: {
    alias: {
      '@': '/src',
      '#': '/types'
    }
  },
  server: {
    open: true
  },
})
